from flask import Flask, request
from flask_cors import CORS
from dotenv import load_dotenv
import os
import sys
import pymysql
import requests
from datetime import datetime
import uuid
from PIL import Image
import io
import traceback
from flask_restx import Api
from models.database import init_db
from routes import register_routes
from controllers.batch_controller import ns as batch_ns
from controllers.user_controller import ns as user_ns

# 加载环境变量
load_dotenv()

app = Flask(__name__, static_folder='static', static_url_path='/static')
# 修改CORS配置
CORS(app, resources={
    r"/api/*": {
        "origins": "*",
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Authorization", "Content-Type"],
        "expose_headers": ["Authorization", "Content-Type"],
        "supports_credentials": True
    }
})

# 设置 JWT 密钥
app.config['SECRET_KEY'] = os.getenv('JWT_SECRET_KEY', 'your-secret-key-here')

# 创建 API 实例
api = Api(
    app,
    version='1.0',
    title='AI Emoji API',
    description='AI表情包生成系统API'
)

# 导入路由
from api import ns  # 导入命名空间
api.add_namespace(ns)  # 添加命名空间到API，它会自动添加到 /api 前缀
api.add_namespace(batch_ns, path='/api/batch')
api.add_namespace(user_ns, path='/api/user')

@app.before_request
def log_request_info():
    print('\n=== Request Info ===')
    print('Headers:', dict(request.headers))
    print('Method:', request.method)
    print('URL:', request.url)
    print('Body:', request.get_data())
    print('===================\n')

@app.after_request
def log_response_info(response):
    print('\n=== Response Info ===')
    print('Status:', response.status)
    print('Headers:', dict(response.headers))
    print('Body:', response.get_data())
    print('===================\n')
    return response

# 添加错误处理器
@app.errorhandler(500)
def handle_500_error(error):
    print('\n=== Error Info ===')
    print('Error:', str(error))
    print('Traceback:')
    print(traceback.format_exc())
    print('===================\n')
    return {
        'status': 'error',
        'message': '服务器内部错误',
        'detail': str(error)
    }, 500

@app.errorhandler(Exception)
def handle_exception(error):
    print('\n=== Exception Info ===')
    print('Exception:', str(error))
    print('Type:', type(error).__name__)
    print('Traceback:')
    print(traceback.format_exc())
    print('===================\n')
    return {
        'status': 'error',
        'message': '服务器异常',
        'detail': str(error)
    }, 500

# 添加一个测试路由来检查数据库连接
@app.route('/api/test-db')
def test_db():
    try:
        conn = get_db_connection()
        if conn is None:
            return {'status': 'error', 'message': '数据库连接失败'}, 500
        
        cursor = conn.cursor()
        cursor.execute('SHOW TABLES')
        tables = cursor.fetchall()
        
        cursor.execute('SELECT DATABASE()')
        current_db = cursor.fetchone()
        
        cursor.close()
        conn.close()
        
        return {
            'status': 'success',
            'database': current_db[0] if current_db else None,
            'tables': [table[0] for table in tables]
        }
    except Exception as e:
        print('\n=== Database Test Error ===')
        print('Error:', str(e))
        print('Traceback:')
        print(traceback.format_exc())
        print('===================\n')
        return {'status': 'error', 'message': str(e)}, 500

# 添加一个OPTIONS请求的全局处理
@app.route('/api/<path:path>', methods=['OPTIONS'])
def handle_options(path):
    return '', 204

# 主函数部分...

# 配置
db_config = {
    'host': os.getenv('DB_HOST', 'localhost'),
    'user': os.getenv('DB_USER', 'root'),
    'password': os.getenv('DB_PASSWORD', '123456'),
    'database': os.getenv('DB_NAME', 'ai_emoji'),
}

# Hugging Face API配置
HF_API_KEY = os.getenv('HUGGINGFACE_API_KEY')
HF_API_URL = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"

# 文件上传配置
UPLOAD_FOLDER = os.getenv('UPLOAD_FOLDER', 'uploads')
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# 创建输出目录
os.makedirs(os.path.join(os.getcwd(), 'static', 'outputs'), exist_ok=True)

# 数据库连接
# 修改数据库连接函数，添加更好的错误处理
def get_db_connection():
    try:
        print(f"尝试连接数据库：{db_config['database']}")
        conn = pymysql.connect(**db_config)
        print("数据库连接成功")
        return conn
    except pymysql.Error as err:
        print(f"数据库连接错误: {err}")
        if hasattr(err, 'args') and len(err.args) > 0:
            if err.args[0] == 1045:
                print("用户名或密码错误")
            elif err.args[0] == 1049:
                print("数据库不存在")
            elif err.args[0] == 2003:
                print("无法连接到MySQL服务器，请确保MySQL服务已启动")
        return None

def check_db_connection():
    print("正在检查数据库连接...")
    conn = get_db_connection()
    if conn is None:
        print("数据库连接失败")
        return False
    print("数据库连接测试成功")
    conn.close()
    return True

# 初始化数据库表
# 修改init_db函数，添加更详细的错误处理
def init_db():
    try:
        conn = get_db_connection()
        if conn is None:
            print("数据库连接失败，无法初始化数据库")
            return False
            
        cursor = conn.cursor()
        
        # 读取SQL文件
        try:
            with open('database/init.sql', 'r', encoding='utf-8') as f:
                sql_commands = f.read().split(';')
        except FileNotFoundError:
            print("找不到初始化SQL文件: database/init.sql")
            return False
        except Exception as e:
            print(f"读取SQL文件时出错: {str(e)}")
            return False
            
        # 执行每个SQL命令
        for i, command in enumerate(sql_commands):
            if command.strip():
                try:
                    cursor.execute(command)
                    print(f"执行SQL命令 {i+1}/{len(sql_commands)}")
                except Exception as e:
                    print(f"执行SQL命令时出错: {str(e)}")
                    print(f"问题SQL: {command[:100]}...")
                    conn.rollback()
                    return False
        
        # 添加默认管理员账户
        try:
            # 首先查询user表的结构
            cursor.execute("DESCRIBE user")
            columns = [column[0] for column in cursor.fetchall()]
            print(f"user表的列: {columns}")
            
            # 检查必要的字段是否存在
            required_fields = ['user_id', 'username', 'password', 'email', 'role', 'created_at']
            missing_fields = [field for field in required_fields if field not in columns]
            
            if missing_fields:
                print(f"警告: user表缺少以下字段: {missing_fields}")
                print("尝试修改表结构...")
                
                # 添加缺失的字段
                for field in missing_fields:
                    try:
                        if field == 'password':
                            cursor.execute("ALTER TABLE user ADD COLUMN password VARCHAR(100) NOT NULL DEFAULT 'default_password'")
                        elif field == 'email':
                            cursor.execute("ALTER TABLE user ADD COLUMN email VARCHAR(100)")
                        elif field == 'role':
                            cursor.execute("ALTER TABLE user ADD COLUMN role VARCHAR(20) DEFAULT 'user'")
                        print(f"添加字段 {field} 成功")
                    except Exception as e:
                        print(f"添加字段 {field} 失败: {str(e)}")
                        conn.rollback()
                        return False
            
            admin_id = str(uuid.uuid4())
            admin_password = "admin123"  # 实际应用中应该加密
            
            # 重新查询表结构
            cursor.execute("DESCRIBE user")
            columns = [column[0] for column in cursor.fetchall()]
            print(f"更新后的user表列: {columns}")
            
            # 构建插入语句
            fields = []
            values = []
            params = []
            
            if 'user_id' in columns:
                fields.append('user_id')
                values.append('%s')
                params.append(admin_id)
                
            if 'username' in columns:
                fields.append('username')
                values.append('%s')
                params.append("admin")
                
            if 'password' in columns:
                fields.append('password')
                values.append('%s')
                params.append(admin_password)
                
            if 'email' in columns:
                fields.append('email')
                values.append('%s')
                params.append("admin@example.com")
                
            if 'role' in columns:
                fields.append('role')
                values.append('%s')
                params.append("admin")
                
            if 'created_at' in columns:
                fields.append('created_at')
                values.append('%s')
                params.append(datetime.now())
            
            # 执行插入语句
            sql = f"INSERT INTO user ({', '.join(fields)}) VALUES ({', '.join(values)})"
            cursor.execute(sql, params)
            print("添加管理员账户成功")
            
        except Exception as e:
            print(f"添加管理员账户时出错: {str(e)}")
            conn.rollback()
            return False
        
        conn.commit()
        cursor.close()
        conn.close()
        return True
    except Exception as e:
        print(f"数据库初始化过程中出错: {str(e)}")
        print(traceback.format_exc())
        return False

# 修改主函数，添加更详细的错误处理
# 修改主函数部分
if __name__ == '__main__':
    try:
       
        print("正在启动 Flask 服务...")
        app.run(
            debug=True,
            port=5000,
            use_reloader=False,
            host='0.0.0.0'
        )
    except Exception as e:
        print("="*50)
        print("启动服务时出错:")
        print(f"错误类型: {type(e).__name__}")
        print(f"错误信息: {str(e)}")
        print("详细错误信息:")
        print(traceback.format_exc())
        print("="*50)
        sys.exit(1)

